package com.hua.androidibeaconlib;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * iBeacon管理类，主要为方便客户端使用IBeaconService类提供的功能
 * @author liuzhenhua
 *
 */
public class IBeaconManager {

	 private final ServiceConnection mConnection = new ServiceConnection() {
	        public void onServiceConnected(ComponentName className, IBinder service) {
	        	mService = ( (IBeaconService.IBeaconBinder)service ).getService();
	        	mService.setConsumer(mConsumer);
	        	mService.setScanInterval(IBeaconManager.this.period);
	        	
	        }
	        public void onServiceDisconnected(ComponentName className) {
	        	mService=null;
	        }
	};
	private int period;
	private IBeaconConsumer mConsumer;
	private IBeaconService mService;
	private static IBeaconManager mIBeaconManager;
	private static Context mContext;
	public static IBeaconManager getInstanceForApplication(Context ctx){
		if(mIBeaconManager==null){
			mIBeaconManager=new IBeaconManager();
		}
		mContext=ctx;
		return mIBeaconManager;
	}
	
	private IBeaconManager(){
		
	}
	
	public void bind(IBeaconConsumer consumer){
		mConsumer=consumer;
		mContext.bindService(new Intent(mContext, IBeaconService.class), mConnection, Context.BIND_AUTO_CREATE);
	}
	
	public void unBind(IBeaconConsumer consumer){
		if(consumer==mConsumer){
			mConsumer=null;
			mService.setConsumer(null);
			mContext.unbindService(mConnection);
		}
	}
	
	public void setPeroid(int period){
		if(mService==null){
			this.period=period;
		}else{
			mService.setScanInterval(period);
		}
	}

    public int getPeroid(){
        return period;
    }
	
}
